import RTCClass from './RTCUtils.js';

// const ip = "172.16.12.37"
const ip = "www.kairos-k.cn"
const roomId = 123
const userId = new Date().getTime()
console.log("我的id-----", userId)

class RTCWebSocketClass {
    constructor(videoDomList, localStream = null) {
        // socket连接
        this.socket = new WebSocket(
            `wss://${ip}/signal/${roomId}/${userId}/0`
            // `ws://${ip}:8087/signal/${roomId}/${userId}/0`
        );
        this.userId = userId;
        // 回调方法
        // socket.onopen = this.onSocketOpen;
        // this.socket.onmessage = onSocketMessage;
        // this.socket.onclose = this.onSocketClose;
        // this.socket.onerror = this.onSocketError;
        this.socket.onmessage = this.onSocketMessage;

        this.rtcClassMap = new Map();

        this.videoDomList = videoDomList;
        // 如果发送本地的流，则需要发送给所有人
        this.localStream = localStream;
    }

    // 获取RTCClass方法
    getRtcClass = (targetUid) => {
        // 进行字符串转换处理，防止由于精度原因键发生变化
        let currentTargetUid = String(targetUid)
        let curretRtcClass = this.rtcClassMap.get(currentTargetUid);

        if (!curretRtcClass) {
            // 这里创建的数量应该不大于可以使用video
            let videoDom = this.videoDomList[this.rtcClassMap.size];
            curretRtcClass = new RTCClass(videoDom, this.userId, targetUid, this.socket, this.localStream);
            console.log(videoDom, "获取的盒子信息", this.localStream, "本地流的信息")
            this.rtcClassMap.set(currentTargetUid, curretRtcClass);
        }
        return curretRtcClass;
    }

    // WebSocket消息事件，服务器返回的消息
    onSocketMessage = async (event) => {
        const message = JSON.parse(event.data);
        console.log("打印WebSocket消息事件信息--", message);

        // 当有用户加入房间时，向所有人广播
        if (message.type == "join") {
            // 对于非接受到本人自己加入的信息，其它人都进行rtc连接建立
            if (message.data.userId != this.userId) {
                let currentTargetUid = message.data.userId;
                let rtcClass = this.getRtcClass(currentTargetUid);
                let offer = await rtcClass.createOffer();
                let sendObj = JSON.stringify({
                    type: "offer",
                    targetUid: currentTargetUid,
                    userId: this.userId,
                    offer: offer,
                });
                this.socket.send(sendObj);
            }
        } else if (message.type == "roomUserList") {
            console.log("打印roomUserList结--果", message);
            // 除了自己外，和其它人建立连接
            message.data.forEach(async (i) => {
                if (i.userId != this.userId) {
                    let currentTargetUid = i.userId;
                    let rtcClass = this.getRtcClass(currentTargetUid);
                    let offer = await rtcClass.createOffer();
                    let sendObj = JSON.stringify({
                        type: "offer",
                        targetUid: currentTargetUid,
                        userId: this.userId,
                        offer: offer,
                    });
                    this.socket.send(sendObj);
                }
            });
        } else if (message.type == "offer") {
            console.log("打印接收到的offer", message);
            let currentTargetUid = message.data.userId;
            let rtcClass = this.getRtcClass(currentTargetUid);
            // 设置接收到的offer为远程描述，发送answer
            rtcClass.setRemoteDescription(JSON.stringify(message.data.offer));
            // 初始化回答
            let answer = await rtcClass.createAnswer();
            // 发送回答
            let sendObj = JSON.stringify({
                type: "answer",
                targetUid: currentTargetUid,
                userId: this.userId,
                offer: answer,
            });
            this.socket.send(sendObj);
        } else if (message.type == "answer") {
            console.log("打印answer结果", message);
            let currentTargetUid = message.data.userId;
            let rtcClass = this.getRtcClass(currentTargetUid);
            // 将回答answer放入到远程描述中
            rtcClass.setRemoteDescription(JSON.stringify(message.data.offer));
            console.log("rtcClass.candidateListrtcClass.candidateList", rtcClass.candidateList)
            // // 循环发送自身的候选地址
            // for (let i of rtcClass.candidateList) {
            //     // 发送出去
            //     let sendObj = JSON.stringify({
            //         type: "candidate",
            //         targetUid: currentTargetUid,
            //         userId: this.userId,
            //         candidate: i,
            //     });
            //     console.log("发送候选地址------", rtcClass.candidateList)
            //     this.socket.send(sendObj);
            // }
        } else if (message.type == "candidate") {
            // 添加candidate
            console.log("获取到了candidate", message);
            let currentTargetUid = message.data.userId;
            let rtcClass = this.getRtcClass(currentTargetUid);
            rtcClass.addCandidate(JSON.stringify(message.data.candidate));
        }
    }
}


export default RTCWebSocketClass;